package com.topboya.linker.ui.adapter;

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.topboya.linker.R;
import com.topboya.linker.diyview.SelectCustomerDialog;
import com.topboya.linker.model.response.CustomerByOrgIdResponse;
import com.topboya.linker.model.response.FollowUserLateResponse;
import com.topboya.linker.model.response.OrganizationResopnse;
import com.topboya.linker.model.response.SelectFileResponse;
import com.topboya.linker.model.response.VisitTypeResponse;
import com.topboya.linker.model.save.VisitCustomerBean;
import com.topboya.linker.ui.activity.CreateTaskActivity1;
import com.topboya.linker.ui.activity.FollowUserAcitivity;
import com.topboya.linker.ui.activity.SellectProductInforActivity;
import com.topboya.linker.ui.activity.VisiTypeActivity;
import com.topboya.linker.ui.presenter.CreateTaskPrensenter;
import com.topboya.linker.utils.LogUtils;
import com.topboya.linker.utils.UIUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

public class CreateTask1Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

    private static final String TAG = "CreateTask1Adapter:";
    private CreateTaskActivity1 mActivity;
    private ArrayList<String> mList;
    private List<CustomerByOrgIdResponse.DepartmentList> departmentList;
    private List<String> alldepartmentList;
    private View footerview;
    private LinearLayout ll_add_customer;
    private Button btn_create_task;
    private TextView tv_startime;
    private TextView tv_followuser;
    private String addstring = "请选择客姓名";
    private int allsize ;
    private VisitCustomerBean visitCustomerBean ;
    private List<VisitCustomerBean.CusList> cusLists;
    private OrganizationResopnse.DocDetailInfoList docDetailInfo;
    private ArrayList<FollowUserLateResponse.LateUser> selectsameDepartLists;
    private CreateTaskPrensenter createTaskPrensenter;


    public CreateTask1Adapter(CreateTaskActivity1 mActivity,CreateTaskPrensenter createTaskPrensenter, ArrayList<String> selectepartnameList,List<CustomerByOrgIdResponse.DepartmentList> departmentList, View footerview,OrganizationResopnse.DocDetailInfoList docDetailInfo) {

        if (selectepartnameList == null) {
            throw new IllegalArgumentException("model Data must not be null");
        }
        this.mActivity = mActivity;
        mList = selectepartnameList;
        this.departmentList =departmentList;
        this.docDetailInfo =docDetailInfo;
        this.createTaskPrensenter =createTaskPrensenter;
        this.footerview = footerview;
//        用于保存条目的每一条目信息
        visitCustomerBean =new VisitCustomerBean();
        cusLists = new ArrayList<>();
        initUserSelected();
        initFootvier();

    }


    private void initFootvier() {

        ll_add_customer = footerview.findViewById(R.id.ll_add_customer);
        btn_create_task = footerview.findViewById(R.id.btn_create_task);
        tv_startime = footerview.findViewById(R.id.tv_startime);
        tv_followuser = footerview.findViewById(R.id.tv_followuser);
        ll_add_customer.setOnClickListener(v -> {

            if (mList.size() >=allsize) {

                UIUtils.showToast("没有可添加的用户了");
            }else {

//                点击添加用户，可以添加就添加一个用户，后面获取到用户名在替换
                mList.add("请选择客姓名");
                notifyDataSetChanged();
            }
        });

        tv_startime.setOnClickListener(v -> starttimeClick());
        tv_followuser.setOnClickListener(v -> {

            Intent intent = new Intent(mActivity,FollowUserAcitivity.class);
            mActivity.startActivityForResult(intent,1003);
            mActivity.setonActivityResultFollowUserListenr(selectsameDepartLists ->{

                LogUtils.v(TAG + "selectsameDepartLists:"+selectsameDepartLists.toString());
                this.selectsameDepartLists  =selectsameDepartLists;
                String  followName="";
                for (int i=0;i < selectsameDepartLists.size();i++){

                    followName =selectsameDepartLists.get(i).getName()+","+followName;
                }
                tv_followuser.setText(followName);
              });

        });

        btn_create_task.setOnClickListener(v -> {

             LogUtils.v(TAG + "result:"+visitCustomerBean.toString());
            Gson gson = new GsonBuilder().disableHtmlEscaping().create();
            String cusList = gson.toJson(visitCustomerBean);
            cusList =cusList.substring(11, cusList.length()-1);
            LogUtils.v(TAG + "cusList:"+cusList);
            String orgId = docDetailInfo.getId();
            String orgName = docDetailInfo.getOrgName();
//            String createDate = AndroidUtils.getCurrentTimeSH();
            String timeUse ="30";
            String startTime = startime;
            String followName ="";
            String followId = "";
            String remarks = "";
            String Mflage ="M";
            for (int i=0;i < selectsameDepartLists.size();i++){

                 followName =selectsameDepartLists.get(i).getName()+","+followName;
                 followName =followName.substring(0, followName.length()-1);
                 followId =selectsameDepartLists.get(i).getUserId()+","+followId;
                 followId =followId.substring(0, followId.length()-1);
            }
            LogUtils.v(TAG+"orgId:"+orgId);
            LogUtils.v(TAG+"orgName:"+orgName);
//            LogUtils.v(TAG+"createDate:"+createDate);
            LogUtils.v(TAG+"timeUse:"+timeUse);
            LogUtils.v(TAG+"startTime:"+startTime);
            LogUtils.v(TAG+"cusList:"+cusList);
            LogUtils.v(TAG+"followName:"+followName);
            LogUtils.v(TAG+"followId:"+followId);
            LogUtils.v(TAG+"remarks:"+remarks);
            LogUtils.v(TAG+"Mflage:"+Mflage);
            createTaskPrensenter.createTaskSuccess(orgId,orgName,null,timeUse,startTime,"",cusList,followName,followId,remarks,Mflage);

        });

    }

   private String startime;
    private void starttimeClick() {

        TimePickerView pvTime = new TimePickerBuilder(mActivity, (date, v1) -> {

              startime =  getLastTime(date);

        })      .setType(new boolean[]{true, true, true, true, true, false})
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setLabel("","","","","","")
                .build();
        pvTime.show();
    }

    //获取最终时间，这个应该修改时间选择器源码，这样做不是很好
    private String getLastTime(Date date) {

        String time[] = getTime(date).split(":");
        String secondes = String .valueOf(Integer.parseInt(time[1] )*10);
        String time1 = time[0] + ":"+secondes+":00";
        return time1;
    }

    private String getTime(Date date) {
        //可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return format.format(date);
    }
    //  初始化已经被选择的数据

    public void initUserSelected(){

        //      保存部门下下面所有的客户信息
         alldepartmentList = new ArrayList<>();
        for (int i=0;i <departmentList.size();i++){

            alldepartmentList.add(departmentList.get(i).getCusName());
        }
     //存储总数据大小，总共就可以添加这么多客户
        allsize = alldepartmentList.size();
//        求差集 表示没有被选中的客户还可以继续添加
        alldepartmentList.removeAll(mList);
        LogUtils.v(TAG +alldepartmentList.toString());

    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

        View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.create_task_item, viewGroup, false);
        return new CreateTask1Adapter.ListItemViewHolder(itemView);

    }
    //绑定界面，设置监听
    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int i) {
//         建造每一个条目对象，并且添加数据
         VisitCustomerBean.CusList  cusList= visitCustomerBean.new CusList();
        //设置条目状态
        ((CreateTask1Adapter.ListItemViewHolder) holder).tv_sustomer_name.setText(mList.get(i));
        ((ListItemViewHolder) holder).view_line.setVisibility((i==0)?View.GONE:View.VISIBLE);
        ((ListItemViewHolder) holder).tv_delete.setVisibility((i==0)?View.GONE:View.VISIBLE);
          itemViewClick(holder ,i,cusList);
//          初始化设置每一个条目的信息
          cusList.setCusName(mList.get(i));
          cusList.setCusId(getIDFromname(mList.get(i)));
          cusList.setSwfwType("");
          cusLists.add(cusList);
          visitCustomerBean.setCusList(cusLists);
    }

    String visitypelabel=null;
    String visitypevalue =null;
    String filesId ="";
    String productIds="";
    private void itemViewClick(RecyclerView.ViewHolder holder, int i,  VisitCustomerBean.CusList  cusList) {


        ((ListItemViewHolder) holder).tv_tasktype.setOnClickListener(v -> visiTypeClick((ListItemViewHolder) holder, cusList));
        ((ListItemViewHolder) holder).tv_product.setOnClickListener(v -> {

            Intent intent = new Intent(mActivity,SellectProductInforActivity.class);
            mActivity.startActivityForResult(intent,1002);
            mActivity.setonActivityResultListenr((visittypelist, productDetailInfoLists, fileListss) -> {

                if (productDetailInfoLists.size() >1){
                    for (int j=0;j <productDetailInfoLists.size();j++){

                        productIds = productDetailInfoLists.get(j).getId()+","+productIds;
                    }
                    productIds =productIds.substring(0, visitypevalue.length()-1);

//                    大于1就显示图片和数量
                    ((ListItemViewHolder) holder).tv_product.setText(String.valueOf(productDetailInfoLists.size()));

                }else {
                    productIds = productDetailInfoLists.get(0).getId();
//                     等于1的话就显示产品名称
                    ((ListItemViewHolder) holder).tv_product.setText(productDetailInfoLists.get(0).getProductName());
                    ((ListItemViewHolder) holder).tv_product.setCompoundDrawables(null,null,null,null);
                }
                cusList.setProductIds(productIds);
                int size=0;
                List<SelectFileResponse.FileList> fileLists;
                if (fileListss.size() >0){

                    for (int j=0;j<fileListss.size();j++){
                        size=fileListss.get(i).size()+size;
                        fileLists = fileListss.get(i);
                        for (int k =0 ;k < fileLists.size();k++){

                            filesId = filesId+ fileLists.get(k).getId();
                        }
                    }
                    filesId =filesId.substring(0, filesId.length()-1);
                    cusList.setFilesId(filesId);
                    cusList.setFileNum(String.valueOf(size));
//                    大于0 就说明有资料，小于则反之
                    ((ListItemViewHolder) holder).tv_file.setText(String.valueOf(size));

                }else {
                    ((ListItemViewHolder) holder).tv_file.setVisibility(View.GONE);
                }
            });

        });

        ((ListItemViewHolder) holder).tv_delete.setOnClickListener(v -> {
//             先判断要添加的用户是不是叫做"请添加用户"，
//             如果是叫做"请添加用户",就不添加进可选名字，这样就可以维护总数不变
             if (!mList.get(i).equals(addstring)) alldepartmentList.add(mList.get(i));
               mList.remove(i);
              notifyDataSetChanged();

        });
        ((ListItemViewHolder) holder).tv_sustomer_name.setOnClickListener(v ->showSelectDialog((ArrayList<String>) alldepartmentList, (ListItemViewHolder) holder, cusList,i));
    }

    private void visiTypeClick(ListItemViewHolder holder, VisitCustomerBean.CusList cusList) {

        Intent intent = new Intent(mActivity,VisiTypeActivity.class);
        mActivity.startActivityForResult(intent,1001);
        mActivity.setonActivityResultListenr((visittypelist, productDetailInfoLists, fileListss) -> visiTypesetting(holder, cusList, visittypelist));
    }

    private void visiTypesetting(ListItemViewHolder holder, VisitCustomerBean.CusList cusList, ArrayList<VisitTypeResponse.Data> visittypelist) {
        for(int j =0;j <visittypelist.size();j ++){

            visitypelabel = visittypelist.get(j).getLabel()+","+visitypelabel;
            visitypevalue = visittypelist.get(j).getValue()+","+visitypevalue;
        }
//            去除最后一个逗号和null（，null）
        visitypelabel =visitypelabel.substring(0, visitypevalue.length()-5);
        visitypevalue =visitypevalue.substring(0, visitypevalue.length()-5);
        holder.tv_tasktype.setText(visitypelabel);
        cusList.setVisitType(visitypevalue);
        LogUtils.v(TAG + cusList.getVisitType());
    }

    @Override
    public int getItemCount() {
        return mList == null ? 0 : mList.size();
    }



    public class ListItemViewHolder extends RecyclerView.ViewHolder{

        //ViewHolder
        TextView tv_sustomer_name;
        TextView  tv_tasktype;
        TextView  tv_product;
        TextView  tv_file;
        TextView  tv_delete;
        View view_line;

        ListItemViewHolder(View view) {
            super(view);
            this.tv_sustomer_name = view.findViewById(R.id.tv_sustomer_name);
            this.tv_tasktype = view.findViewById(R.id.tv_tasktype);
            this.tv_product = view.findViewById(R.id.tv_product);
            this.tv_delete = view.findViewById(R.id.tv_delete);
            this.view_line = view.findViewById(R.id.view_line);
            this.tv_file = view.findViewById(R.id.tv_file);

        }

    }

    private void showSelectDialog(ArrayList<String> tempdepartmentList,ListItemViewHolder holder,VisitCustomerBean.CusList cusList,int positon) {

        final SelectCustomerDialog selectCustomerDialog = SelectCustomerDialog.newInstance(tempdepartmentList);
        selectCustomerDialog.show(mActivity.getFragmentManager(), "select");
//        selectCustomerDialog.setCancelable(false);
        selectCustomerDialog.setOnSelectListener(selectPosSet -> {
            selectCustomerDialog.dismiss();
            Iterator<Integer> value = selectPosSet.iterator();
            while (value.hasNext()) {

                int s = value.next();
                holder.tv_sustomer_name.setText(alldepartmentList.get(s));
                cusList.setCusName(alldepartmentList.get(s));
                cusList.setCusId(getIDFromname(alldepartmentList.get(s)));
//              添加一个就把点击位置的名字重置，判断一下是更改名字还是添加，如果是更改的话，就直接重置名字
                if (!mList.get(positon).equals(addstring)){
//                     名字进行交换
                    String name = mList.get(positon);
                    mList.set(positon,alldepartmentList.get(s));
                    alldepartmentList.set(s,name);

                }else {

                    mList.set(positon,alldepartmentList.get(s));
                    // 然后把可添加里面删除
                    alldepartmentList.remove(s);
                }
            }
        });

    }

    public String getIDFromname(String cusname){

        String cusID = null;
        for (int i=0 ;i <departmentList.size(); i++){

            if (cusname.equals(departmentList.get(i).getCusName())){

                cusID  = departmentList.get(i).getId();
            }
        }
        return cusID;
    }

}
